<?php
namespace App\Http\Controllers\CRM;
use App\Order;
use App\Rad_user;
use App\Rad_user_account;
use Illuminate\Http\Request;

use App\Common\ErrorDefine;

use App\Radacct;
use App\Radcheck;
use App\Radgroupcheck;
use App\Radreply;
use App\Radusergroup;
use App\Rad_manage;
use App\Radgroupreply;
use App\Rad_users;
use App\Rad_account;
use App\Rad_merge_data;
use DB;
use App\Rad_manage_discount;
use App\Rad_order;
use App\Line;
use App\Agent;
use App\Teamqq;

use App\Manage_user_list;
use App\Discount;
use App\Http\Controllers\Controller;
use Redis;
use App\Terrace;
use App\Http\Controllers\CRM\PublicController;

class UpdateUserController extends Controller
{

//
    public function updateOrder()
    {
//        $order = Rad_order::where('agent_id',1)->where('status',1)->where('month','>',0)->get();
//        foreach($order as $value)
//        {
//            $users = Rad_users::find($value->user_id);
//            if($users != NULL)
//            {
//                $users->total_consumption = $users->total_consumption+$value->price;
//                $users->save();
//            }
//            $value->date = $value->date*$value->month*30;
//            $value->save();
//        }
    }


    //   单个账号续费
    public function doAccountRenew(Request $request)
    {
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        //  名称
        if(!$request->has('username') || empty($request->input('username')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $username = $request->input('username');

        //  密码
        if(!$request->has('password') || empty($request->input('password')))
        {
            self::ShowError(ErrorDefine::SHORT_OF_PASSWORD);
            return;
        }
        $password = $request->input('password');


        //   用户token
        if(!$request->has('token') || empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        //    续费时间
        if(!$request->has('renew_date') || empty($request->input('renew_date')))
        {
            self::ShowError(ErrorDefine::DATE_NOT_EXIST);
            return;
        }
        $renew_date= $request->input('renew_date');

        if($renew_date<=0) {
            self::ShowError(ErrorDefine::INVALID_DATE);
            return;
        }

        //  订单号
        if(!$request->has('order_id') || empty($request->input('order_id')))
        {
            self::ShowError(ErrorDefine::ORDER_NO_NOT_EXIST);
            return;
        }
        $order_no = $request->input('order_id');

        //  续费的钱数
        if(!$request->has('renew_money') || empty($request->input('renew_money')))
        {
            self::ShowError(ErrorDefine::PEICE_NOT_EXIST);
            return;
        }
        $renew_money = $request->input('renew_money');

        // 续费日期类型
        if(!$request->has('renew_type') || empty($request->input('renew_type')))
        {
            self::ShowError(ErrorDefine::PEICE_NOT_EXIST);
            return;
        }
        $renew_type = $request->input('renew_type');

        $public = new PublicController();

        //   获取用户ID
        $user = $public->getTokenById($token);
        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }

        $manage_id =  $user[0]['manage_id'];

        if( $user[0]['balance'] < $renew_money)
        {
            return self::ShowError(ErrorDefine::BALANCE_NOT_ENGOUTH);
        }

        $date = 0;
        switch ($renew_type) {
            case '日':
                $expired_at = time() + 86400 * $renew_date * 1;
                $date = $renew_date*1;
                break;
            case '周':
                $expired_at = time() + 86400 * $renew_date * 7;
                $date = $renew_date*7;
                break;
            case '月':
                $expired_at = time() + 86400 * $renew_date * 30;
                $date = $renew_date*30;
                break;
        }

        $where = [];
        $where['username'] = $username;
        $where['attribute'] = 'Expiration';
        $where['op'] = ':=';

        $where2 = [];
        $where2['username'] = $username;

        $rad = Radcheck::where($where)->get();
        $ret = Rad_users::where($where2)->get();

        if(empty($rad[0]))
        {
            self::ShowError(ErrorDefine::ACCOUNT_NOT_EXIST);
            return;
        }

        if(strtotime($rad[0]->value) > time())
        {
            $expired_at = strtotime($rad[0]->value) + $expired_at - time();
        }

        $time = date("d M Y H:i:s ",$expired_at);

        $rad[0]->value=$time;
        $rad[0]->save();

        $ret[0]->updated_at = date('Y-m-d H:i:s',time());
        $ret[0]->expired_at = date('Y-m-d H:i:s',$expired_at);
        $ret[0]->account_type = '付费';
        $ret[0]->balance = $renew_money;        //  最近一次续费金额
        $ret[0]->days = $date;              // 最近一次续费天数
        $ret[0]->save();

        $oder = [];
        $order['balance'] = $user[0]['balance']-$renew_money;
        $order['date'] =$date;              //  开通天数
        $order['price'] =$renew_money;
        $order['status'] =1;
        $order['account_type'] = '付费';
        $order['connect_num'] =$ret[0]['con_max'];
        $order['user_id'] = $manage_id;
        $order['order_no'] =$order_no;
        $order['created_at'] = date('Y-m-d H:i:s',time());
        $order['updated_at'] = date('Y-m-d H:i:s',time());
        $order['to_user'] =  $ret[0]->user_id;

        Rad_order::insertGetId($order);
        if($ret[0]['pid'] > 0)
        {
            $parent = Rad_users::where('user_id',$ret[0]['pid'])->first();

            if($parent != NULL)
            {
                $parent->total_consumption =  $parent->total_consumption + $renew_money;
                $parent->save();
            }
        }

        $user = Rad_manage::find($manage_id);
        $user->balance = $user->balance - $renew_money;
        $user->save();


        return self::ShowMessage();
    }


    //   批量续费
    public function doChildAccountbatchRenew(Request $request)
    {
        $basic = [];    //  基础
        $middle=[];     //  中级
        $height=[];     //  高级
        $pid = 0;
        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        //  父级信息
        if($request->has('pid') && !empty($request->input('pid')))
        {
            $pid = $request->input('pid');
        }



        //  续费天数
        if(!$request->has('batch-renew-date') || empty($request->has('batch-renew-date')))
        {
            self::ShowError(ErrorDefine::INVALID_DATE);
            return;
        }
        $date = $request->input('batch-renew-date');


        //   续费日期类型
        if(!$request->has('batch-renew-date-type') || empty($request->has('batch-renew-date-type')))
        {
            self::ShowError(ErrorDefine::DATE_TYPE_NOT_EXIST);
            return;
        }
        $date_type = $request->input('batch-renew-date-type');

        //  续费价格
        if(!$request->has('all-renew-price') || empty($request->has('all-renew-price')))
        {
            self::ShowError(ErrorDefine::PEICE_NOT_EXIST);
            return;
        }
        $price = $request->input('all-renew-price');

        if($price <=0)
        {
            self::ShowError(ErrorDefine::INVALID_PRICE);
            return;
        }


        $public  = new PublicController();

        //  获取用户信息
        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID
        $manage = $public->getTokenById($token);

        if(empty($manage))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }
        $manage_id =  $manage[0]['manage_id'];


        //  判断余额是否充足
        if($manage[0]['balance'] < $price)
        {
            self::ShowError(ErrorDefine::BALANCE_NOT_ENGOUTH);
            return;
        }

        $renew_time = 0;
        //   续费时间
        switch($date_type)
        {
            case '日': $renew_time = $date * 86400 *1;break;
            case '周': $renew_time = $date * 86400 *7;break;
            case '月': $renew_time = $date * 86400 *30;break;
            default:  self::ShowError(ErrorDefine::DATE_TYPE_NOT_EXIST);return;break;

        }

        //   基础套餐数据
        if($request->has('basic_type_id') && !empty($request->has('basic_type_id')) )
        {
            $basic['user_id'] = trim($request->input('basic_type_id'),',');
        }

        if($request->has('basic-type-price') && !empty($request->has('basic-type-price')) )
        {
            $basic['price'] = $request->input('basic-type-price');
        }



        //   中级套餐数据
        if($request->has('middle_type_id') && !empty($request->has('middle_type_id')) )
        {
            $middle['user_id'] = trim($request->input('middle_type_id'),',');
        }

        if($request->has('middle-type-price') && !empty($request->has('middle-type-price')) )
        {
            $middle['price'] = $request->input('middle-type-price');
        }


        //   高级套餐数据

        if($request->has('height_type_id') && !empty($request->has('height_type_id')) )
        {
            $height['user_id'] = trim($request->input('height_type_id'),',');
        }

        if($request->has('height-type-price') && !empty($request->has('height-type-price')) )
        {
            $height['price'] = $request->input('height-type-price');
        }




        if(!empty($basic))
        {
            $ret = self::RenewAccount($basic,$renew_time,$manage_id,$date);
        }


        if(!empty($middle))
        {
            $ret = self::RenewAccount($middle,$renew_time,$manage_id,$date);
        }


        if(!empty($height))
        {
            $ret = self::RenewAccount($height,$renew_time,$manage_id,$date);
        }



        return self::ShowMessage();


    }



    static function RenewAccount($array,$renew_time,$manage_id,$date)
    {

        $public  = new PublicController();
        $expired_at = 0;

        //  更新用户信息
        $manage = Rad_manage::find($manage_id);
        $id = explode(',',$array['user_id']);

        $count = Rad_users::whereIn('user_id',$id)->sum('con_max');

        $price = (int)ceil((int)($array['price']) / $count);



        foreach($id as $value)
        {
            $users = Rad_users::find($value);

            if(strtotime($users->expired_at) > time())
            {
                $expired_at =  strtotime($users->expired_at) + $renew_time;
            }else{
                $expired_at = time() + $renew_time;
            }
            $users->expired_at = date('Y-m-d H:i:s',$expired_at);
            $users->balance = $price*$users->con_max;
            $users->account_type = '付费';
            $users->days = $date;
            $users->save();


            $time = date("d M Y H:i:s ",$expired_at);
            $radcheck =  Radcheck::where('username',$users->username)->where('attribute','Expiration')->first();
            if($radcheck != NULL)
            {
                $radcheck->value = $time;
                $radcheck->save();
            }

            $order = [];
            $order['order_no'] = $public->createUuid();     //  订单号
            $order['user_id'] =$manage_id ;                 // 客服ID
            $order['pay_channel'] =2;                       //  支付通道
            $order['account_type'] = '付费';                 //  账户类型
            $order['date'] =$date;                          //  账户开通时间
            $order['to_user'] =$value;                      //  用户ID
            $order['price'] =$price*$users->con_max;                        //  价格
            $order['balance'] = $manage->balance - $price*$users->con_max;    //  客服余额
            $order['created_at'] = date('Y-m-d H:i:s',time());  //  创建时间
            $order['updated_at'] = date('Y-m-d H:i:s',time());  //  更新时间
            $order['status'] = 1;                               //  订单状态
            $order['connect_num'] = $users->con_max;            //  订单状态
            $ret = Rad_order::insertGetId($order);

            $manage->balance =  $manage->balance - $price;
            $manage->save();

            if($users->pid !=0)
            {
                $parent = Rad_users::where('pid',$users->pid)->first();
                if($parent != NULL)
                {
                    $parent->total_consumption =  $parent->total_consumption + $price*$users->con_max;
                    $parent->save();
                }
            }


        }

        return true;
    }





    //  修改父级信息
    public function doUpdateParentAccount(Request $request)
    {
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        $where=  [];

        //   用户token
        if(!$request->has('token') || empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');


        $public = new PublicController();

        //   获取用户ID
        $user = $public->getTokenById($token);
        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }


        //  用户名
        if(!$request->has('username') || empty($request->input('username')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }

        $where['username'] = trim($request->input('username'));

        // 密码
        if(!$request->has('password') || empty($request->input('password')))
        {
            self::ShowError(ErrorDefine::SHORT_OF_PASSWORD);
            return;
        }
        $where['value'] = trim($request->input('password'));

        // 密码
        if(!$request->has('qq') || empty($request->input('qq')))
        {
            self::ShowError(ErrorDefine::INVALID_QQ);
            return;
        }

        $qq = trim($request->input('qq'));


        //  账号ID
        if(!$request->has('user_id') || empty($request->input('user_id')))
        {
            self::ShowError(ErrorDefine::ACCOUNT_ID_NOT_EXIST);
            return;

        }

        $user_id = $request->input('user_id');

        if(!$request->has('manage_id') || empty($request->input('manage_id')))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;

        }

        $manage_id = $request->input('manage_id');

        $remark = '';
        if($request->has('remark'))
        {
            $remark = $request->input('remark');
        }


        // 获取用户信息
        $user = Rad_users::find($user_id)->toArray();


        //   检测新的用户名是否被使用
        $info = Radcheck::where('username',$where['username'])->get()->toArray();


        if(!empty($info))
        {
            if($user['username'] != $info[0]['username'])
            {
                self::ShowError(ErrorDefine::ACCOUNT_IS_EXIST);
                return;
            }
        }


        //  更新用户表内用户信息
        $ret1 = Radcheck::where('username',$user['username'])->where('id',$user_id)->update($where);

        $ret2 = Radcheck::where('username',$user['username'])->where('attribute','=','Expiration')->update(['username'=>$where['username']]);

        // 更新用户组信息
        $ret3 = Radusergroup::where('username',$user['username'])->update(['username'=>$where['username']]);

        Rad_users::where('username',$user['username'])->where('user_id','=',$user_id)->update(
            ['username'=>$where['username'],'password'=>$where['value'],'manage_id'=>$manage_id,'remark'=>$remark,'qq'=>$qq]
        );

        return self::ShowMessage();


    }

    //   修改子账号信息
    public function doUpdateChildAccount(Request $request)
    {
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        $where=  [];
        $users=  [];
        //  用户名
        if(!$request->has('username') && !empty($request->input('username')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $where['username'] = trim($request->input('username'));
        $users['username'] = trim($request->input('username'));


        // 密码
        if(!$request->has('password') && !empty($request->input('password')))
        {
            self::ShowError(ErrorDefine::SHORT_OF_PASSWORD);
            return;
        }

        $where['value'] = trim($request->input('password'));
        $users['password'] = trim($request->input('password'));


        //  账号ID
        if(!$request->has('account_id') && !empty($request->input('account_id')))
        {
            self::ShowError(ErrorDefine::ACCOUNT_ID_NOT_EXIST);

        }
        $user_id = $request->input('account_id');

        if($request->has('remark'))
        {
            $users['remark'] = trim($request->input('remark'));

        }

        $speed = '';
        //  限速的速度
        if($request->has('speed') && !empty($request->input('speed')))
        {
            $speed= trim($request->input('speed'));
        }

        if($request->has('set-meal-type'))
        {
            $users['set_meal_type'] = trim($request->input('set-meal-type'));
        }

        // 获取用户信息
        $user = Rad_users::find($user_id)->toArray();

        //   检测新的用户名是否被使用
        $info = Radcheck::where('username',$where['username'])->get()->toArray();

        if(!empty($info))
        {
            if($user['username'] != $info[0]['username'])
            {
                self::ShowError(ErrorDefine::ACCOUNT_IS_EXIST);
                return;
            }
        }


        if(!empty($speed))
        {
            //  限速修改
            $radreply = Radreply::where('username',$user['username'])->where('attribute','Mikrotik-Rate-Limit')->first();
            if($radreply)
            {
                $radreply->username = $where['username'];
                $radreply->value = $speed;
                $radreply->save();
            }else{
                $radreply = new Radreply();
                $radreply->username = $where['username'];
                $radreply->value = $speed;
                $radreply->save();
            }

        }

        //  更新用户表内用户信息
        $ret1 = Radcheck::where('username',$user['username'])->where('id',$user_id)->update($where);

        $ret2 = Radcheck::where('username',$user['username'])->where('attribute','=','Expiration')->update(['username'=>$where['username']]);

        // 更新用户组信息
        $ret3 = Radusergroup::where('username',$user['username'])->update(['username'=>$where['username']]);

        Rad_users::where('username',$user['username'])->where('user_id','=',$user_id)->update($users);

        return self::ShowMessage();
    }


    /**
     * @param Request $request
     * 绑定子账号
     */
    public function doBindChildAccount(Request $request)
    {
        if(!$request->has('pid') || empty($request->input('pid')))
        {
            self::ShowError(ErrorDefine::INVALID_PID);
            return;
        }

        $pid = $request->input('pid');

        if(!$request->has('userid') || empty($request->input('userid')))
        {
            self::ShowError(ErrorDefine::INVALID_CHILD);
            return;
        }

        $child_id = trim($request->input('userid'),',');
        //   用户token
        if(!$request->has('token') || empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        $public = new PublicController();

        //   获取用户ID
        $user = $public->getTokenById($token);
        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }

        $manage_id = $user[0]['manage_id'];



        $child = explode(',',$child_id);
        $number = count($child);

        $users = Rad_users::where('user_id',$pid)->first();

        $ret = Rad_users::whereIn('user_id',$child)->update(['pid'=>$pid]);

        $total_money = Rad_order::whereIn('to_user',$child)->where('status',1)->sum('price');
        $users->account_num = $users->account_num + $number;
        $users->total_consumption = $users->total_consumption+$total_money;
        $users->save();

        return self::ShowMessage();

    }

    /**
     * @param Request $request
     * 沟通父级账号时间
     */
    public function doCommunicationParentAccount(Request $request)
    {

        //   用户token
        if(!$request->has('token') || empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        $public = new PublicController();

        //   获取用户ID
        $user = $public->getTokenById($token);
        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }

        if(!$request->has('user_id') || empty($request->input('user_id')))
        {
            return self::ShowError(ErrorDefine::ACCOUNT_ID_NOT_EXIST);
        }

        $user_id = $request->input('user_id');


        $manage_id = $user[0]['manage_id'];
        $time = date('Y-m-d H:i:s',time());


        $users = Rad_users::find($user_id);
        $users->communication_time = $time;
        $users->save();
        return self::ShowMessage();

    }



        //   更新数据
    public function updateData()
    {
        $users  = Rad_users::whereIn('terrace_id',['1','6'])->get();

        foreach($users as $value)
        {
            $value->pid = $value->user_id;
            $value->account_num = 1;
            $value->balance = 0;
            $value->save();
        }
    }
}


